<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://code.google.com/p/feather-cm
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class Role extends ActiveRecord
{
	public    $belongsTo   = array('Aro','Aco');
	protected $cachedRoles = array();
	
	function & resolveIDs($aco, $aro=null)
	{
		$this->conditions(array('Aco.aco' => $this->Aco->prefix.$aco));
		if (!empty($aro))
			$this->conditions(array('Aro.aro' => $aro));
		
		$this->process = Q_PROCESS_LIST;
		$rs = $this->findAll('Role.id');
		return $rs;
	}
	
	function & fetchRoles($aco, $aro=null)
	{
		# cached in memory?
		$_md5 = md5($aco.'-'.$aro);
		
		if (isset($this->cachedRoles[$_md5]))
			return $this->cachedRoles[$_md5];
		else
		{
			# cached on disk?
#			$fname = 'perms'.DS.$_md5;
#			$cache = (DEBUG != 2) ? cache($fname, null, '+30 minutes') : null;
			
#			if (!empty($cache)) {
#				$roles = unserialize($cache);
#			}
#			else
#			{
				# not cached: fetching
				$conditions = array('Aco.aco' => $this->Aco->prefix.$aco);
				if (!is_null($aro))
					$conditions['Aro.aro'] = $aro;
				$this->conditions(&$conditions);
				$perms = $this->findAll('Aro.aro, Role.read, Role.write, Role.delete');
				
				$roles = array();
				if (!empty($perms))
				{
					foreach ($perms as $p)
						$roles[$p['Aro']['aro']] =& $p['Role'];
				}
				
				# caching: disk & memory
#				cache($fname, serialize($roles));
				$this->cachedRoles[$_md5] =& $roles;
#			}
			return $roles;
		}
	}
	
	// admin
	
	function create($aro, $aco, $read=null, $write=null, $delete=null)
	{
		$rs = $this->resolveIDs($aco, $aro);
		
		$data = array();
		if (!is_null($read))
			$data['read']   = $read;
		if (!is_null($write))
			$data['write']  = $write;
		if (!is_null($delete))
			$data['delete'] = $delete;
		
		if (!empty($rs))
		{
			$this->id = $rs[0];
			$this->saveFields(&$data);
		}
		else
		{
			$data['aro_id'] = $this->Aro->resolveID($aro);
			if (empty($data['aro_id']))
				$data['aro_id'] = $this->Aro->create($aro);
			
			$data['aco_id'] = $this->Aco->resolveID($aco);
			if (empty($data['aco_id']))
				$data['aco_id'] = $this->Aco->create($aco);
			
			$this->__setData(&$data);
			$this->__save('insert');
		}
		
		return $this->id;
	}
	
	function destroy($aco, $aro=null)
	{
		$rs = $this->resolveIDs($aco, $aro);
		if (!empty($rs))
		{
			$this->conditions(array('id' => &$rs));
			return $this->__delete();
		}
		return true;
	}
	
	// overrides
	
	function __get($name)
	{
		$this->$name = new $name;
		return $this->$name;
	}
}
?>
